<template>
  <div class="mainBox" ref="aa" @scroll="handleScroll">
    <div class="top">
      <div class="top-seach">
        <el-input style="height: 100%; width: 100%;" v-model="seachInput" placeholder="请输入内容或标题"
          @keyup.enter="seachList"></el-input>
        <div class="seach" @click="seachList"></div>
      </div>
    </div>

    <div class="container" id="con">
      <div class="item" v-for="(item,index) in postList" :key="item.id">
        <div class="image-container"  @click="showInfo(item.id,index)">
          <el-icon style="position: absolute;right:7px;top:6px;color:white" v-if="item.postType==2"><VideoPlay /></el-icon>
          <img v-if="item.postType==2" :src="getLinkData(item.imgUrl)[0]+'?spm=qipa250&x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'" alt="image" class="img" @error="handleImageError" />
          <img v-else :src="getLinkData(item.imgUrl)[0]" alt="image" class="img" @error="handleImageError" />
        </div>
        <div class="title">{{ item.title }}</div>
        <div class="author">
          <img :src="item.authorAvatar" class="authorAvatar" @error="handleAvatarError" />
          <div class="authorName">{{ item.authorName }}</div>
          <div class="good">

            <img v-if="item.isgood" src="../../../assets/icon/gooded.png" @click="isNotGood(item.id, index)"
              style="height: 20px; width: 20px" />
            <img v-else src="../../../assets/icon/good.png" @click="isGood(item.id, index)"
              style="height: 20px; width: 20px" />
            <div style="font-size: 12px; margin-left: 2px; color: #424242">{{ item.likeMan }}</div>
          </div>
        </div>
      </div>
    </div>

    <div style="text-align: center; padding-bottom: 20px; color: #424242">
      这已经是全部内容了哦
    </div>
    <!-- <div v-else style="text-align: center; padding-bottom: 20px; color: red" v-loading="loadingMore">pp</div> -->


<el-dialog  destroy-on-close class="custom-dialog"  v-model="dialogTableVisible">
<postInfo :postId="currentPostId"/>
  </el-dialog>


  </div>


</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import postInfo from './postInfo.vue';
import {VideoPlay} from '@element-plus/icons-vue';
import imagesLoaded from 'imagesloaded'; // 图片加载完成检测
import { throttle } from 'lodash-es'; // 节流函数
import { getPostListAPI,PostIsGood,PostIsNotGood,searchPostsAPI } from '../../../api/community';
import useCounter from '../../../stores/pinia';

// 数据相关
const postList = ref([]);
const dialogTableVisible = ref(false)
const seachInput = ref('');
const aa = ref(null);
const pageNo = ref(1);
const allPage = ref(1);
const pageSize = ref(30);
const columnCount = ref(4); // 默认列数
const containerElement = ref(null);
const loadingMore = ref(false);
const counterStore=useCounter()
const currentPostId = ref(null); // 当前选中的帖子ID

// 搜索按钮点击
const seachList = () => {
  console.log('点击了查询按钮');
   // 重置分页和列表数据
  pageNo.value = 1;
  postList.value = [];
  //isSearching.value = true;
  //noMoreData.value = false;
  searchPosts();
};
const searchPosts = async () => {
  if (seachInput.value.trim() === '') {
    await getPostList();
    return;
  }
     try {
    const params = {
      keyword: seachInput.value.trim(), 
      pageNo: 1,
      pageSize: pageSize.value,
      userId: counterStore.userId
    };

    const result = await searchPostsAPI(params);
    console.log('搜索结果:', result.data.data);
    const data = result.data.data;
     if (data.rows.length === 0 && pageNo.value === 1) {
        postList.value = [];
        console.log('没有搜索到相关内容');
     } else {
         allPage.value = Math.ceil(data.total / pageSize.value);
     }if(pageNo.value === 1){
         postList.value = data.rows;
         console.log('当前是第一页数据');
     } else {
        postList.value = [...postList.value, ...data.rows];
      }
  } catch (err) {
    console.error('搜索失败:', err);
  }
}
const isGood=async(id,index)=>{
  const result=await PostIsGood(counterStore.userId,id)
  if(result.data.code==200){
    postList.value[index].isgood=true
    // console.log(postList.value[index].likeMan+1)
    postList.value[index].likeMan += 1
  }
}
const getLinkData = (imgList) => {
  try {
    if (!imgList) return []
    const jsonString = imgList.replace(/'/g, '"');
    const imgList1 = JSON.parse(jsonString);
    // const data = typeof imgList === 'string' ? JSON.parse(imgList) : imgList;

    return imgList1;
  } catch (error) {
    console.error('imgList:', error);
    return [];
  }
}

const isNotGood = async (id, index) => {
  const result = await PostIsNotGood(counterStore.userId, id)
  if (result.data.code == 200) {
    postList.value[index].isgood = false
    postList.value[index].likeMan -= 1
  }
}

const showInfo=(id,index)=>{
  console.log(id,index)
  currentPostId.value = id; // 保存当前选中的帖子ID
  dialogTableVisible.value=true
}

// 处理图片加载失败
const handleImageError = (event) => {
  event.target.src = '../../../assets/picture/default-image.jpg';
};

// 处理头像加载失败
const handleAvatarError = (event) => {
  event.target.src = '../../../assets/picture/default-image.jpg';
};

// 获取帖子列表数据
const getPostList = async () => {
  if (pageNo.value > allPage.value || loadingMore.value) return;
  loadingMore.value = true;

  try {
    const params = {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      userId: counterStore.userId
    };
    const result = await getPostListAPI(params);
    const data = result.data.data;

    allPage.value = Math.ceil(data.total / pageSize.value);
    postList.value = [...postList.value, ...data.rows];
    pageNo.value++;
  } catch (err) {
    console.error('获取帖子失败:', err);
  } finally {
    loadingMore.value = false;
  }
};

// 动态计算列数和 item 宽度
const adjustColumnCountAndItemWidth = () => {
  const con = document.getElementById('con');
  if (!con) return;

  const containerWidth = con.clientWidth;
  const minColumnWidth = 250;
  const count = Math.floor(containerWidth / minColumnWidth);
  columnCount.value = Math.max(2, Math.min(count, 5));
};

// 手动实现瀑布流布局
const layoutItems = () => {
  const con = document.getElementById('con');
  if (!con) return;

  const items = Array.from(con.getElementsByClassName('item'));
  if (items.length === 0) return;

  adjustColumnCountAndItemWidth();
  const cols = columnCount.value;
  const containerWidth = con.clientWidth;
  const itemWidth = (containerWidth - (cols - 1) * 10) / cols;
  const heights = new Array(cols).fill(0);

  items.forEach((item, index) => {
    item.style.width = `${itemWidth}px`;
    const colIndex = index % cols;
    const top = heights[colIndex];
    item.style.position = 'absolute';
    item.style.left = `${colIndex * (itemWidth + 10)}px`;
    item.style.top = `${top}px`;
    heights[colIndex] += item.offsetHeight + 10;
  });

  con.style.height = `${Math.max(...heights)}px`;
};

// resize 监听并重新布局
const throttledResizeHandler = throttle(() => {
  layoutItems();
}, 100);

// scroll 加载更多
const handleScroll = throttle(async () => {
  const el = aa.value;
  if (!el) return;

  const threshold = 800;
  const distanceToBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
  if (distanceToBottom <= threshold) {
    await getPostList();
    setTimeout(() => {
      imagesLoaded(document.getElementById('con'), layoutItems);
    }, 0);
  }
}, 100);

// watch 数据变化后重新布局
watch(
  () => postList.value.length,
  (newLength) => {
    if (newLength > 0) {
      const con = document.getElementById('con');
      imagesLoaded(con, layoutItems);
    }
  },
  { immediate: true }
);

onMounted(async () => {
  containerElement.value = document.getElementById('con');

  window.addEventListener('resize', throttledResizeHandler);
  await getPostList();
  setTimeout(() => {
    imagesLoaded(containerElement.value, layoutItems);
  }, 0);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', throttledResizeHandler);
});
</script>

<style>
.custom-dialog {
  /* background-color: yellowgreen !important; */
  border-radius: 15px !important;
}

.custom-dialog .el-dialog__header {
  display: none !important;
}

.custom-dialog .el-dialog__headerbtn {
  display: none !important;
}

.custom-dialog .el-dialog__body {
  padding: 0 !important;
}
</style>

<style scoped>
.mainBox {
  width: 100%;
  height: calc(100% - 65px);
  padding-top: 65px;
  overflow: auto;
  min-width: 370px;
}

.top {
  position: absolute;
  top: 10px;
  width: 100%;
  display: flex;
  justify-content: center;
  z-index: 999;
}

.top-seach {
  width: 500px;
  height: 45px;
  position: relative;
  border-radius: 200px;
}

:deep(.el-input__wrapper) {
  /* background-color: rgb(250, 250, 250); */
  /* height: 100%; */
  border-radius: 20px;
}

:deep(.el-input__wrapper.is-focus) {
  /* background-color: yellowgreen; */
  /* border-radius: 20px; */
  box-shadow: 0 0 0 1px rgb(2, 87, 121) inset;
}

.seach {
  width: 30px;
  height: 30px;
  position: absolute;
  top: 8px;
  right: 9px;
  background-image: url('../../../assets/icon/seach.png');
  background-size: cover;
  border-radius: 20px;
  cursor: pointer;
}

.seach:hover {
  background-image: url('../../../assets/icon/seach-hover1.png');
}

.container {
  position: relative;
  width: calc(100% - 20px);
  margin: 0 10px;
  /* min-width: 600px; */
}

.item {
  position: absolute;
  margin-bottom: 10px;
  min-width: 150px;
}

.image-container {
  position: relative;
  display: inline-block;
  cursor: pointer;
  border-radius: 15px;
  overflow: hidden;
}

.image-container .img {
  width: 100%;
  display: block;
}

.image-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.37);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-container:hover::before {
  opacity: 1;
}

.title {
  width: calc(100% - 20px);
  font-size: 15px;
  font-weight: 350;
  color: #424242;
  margin: 0 10px;
  line-height: 1.4;
  max-height: calc((1em * 1.4) * 2);
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.author {
  width: calc(100% - 20px);
  margin: 5px 10px 15px;
  display: flex;
  align-items: center;
}

.authorAvatar {
  width: 20px;
  aspect-ratio: 1/1;
  border-radius: 50%;
}

.authorName {
  width: 75%;
  min-width: 50px;
  font-size: 13px;
  font-weight: 350;
  margin-left: 5px;
  color: #424242;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}

.good {
  width: calc(25% - 20px);
  min-width: 52px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  color: #424242;
  cursor: pointer;
}

.custom-dialog {
  width: 500px;
  height: 900px;
  /* position: fixed;
  z-index: 9999; */
  /* background-color: yellowgreen; */
}
</style>